package com.union.session;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.union.entitybean.Category;
import com.union.entitybean.PC;
import com.union.entitybean.Person;
import com.union.entitybean.Personinfo;
import com.union.transfer.BigPerson;

public class PersonBean extends BaseBean {

	public boolean save(boolean isClose, Person person, Personinfo personinfo,
			Collection<Category> selectedList) {
		personDAO.save(person);
		personinfoDAO.save(personinfo);
		for (Iterator<Category> iterator = selectedList.iterator(); iterator
				.hasNext();) {
			Category category = (Category) iterator.next();
			PC pc = new PC();
			pc.setCategory(category);
			pc.setPerson(person);
			pcDAO.save(pc);
		}
		return isClose;
	}

	@SuppressWarnings("unchecked")
	public boolean update(Person person, Personinfo personinfo,
			Collection<Category> selectedList) {
		try {
			pcDAO.deleteByPersonId(person.getPersonId());
		} catch (Exception e) {
			e.printStackTrace();
		}

		Person tmpPerson = personDAO.merge(person);
		personinfo.setPerson(tmpPerson);
		personinfoDAO.merge(personinfo);

//		for (Iterator<Category> iterator = selectedList.iterator(); iterator
//				.hasNext();) {
//			Category category = (Category) iterator.next();
//			PC pc = new PC();
//			pc.setCategory(category);
//			pc.setPerson(person);
//			pcDAO.save(pc);
//		}
		return true;
	}

	@SuppressWarnings("unchecked")
	public List<BigPerson> findByCateList(ArrayList<Category> selectedList) {
		String str = "";
		if (selectedList.size() == 0) {
			;
		} else if (selectedList.size() == 1) {
			Category category = (Category) selectedList.iterator().next();
			str += category.getCateId();
		} else {
			for (int i = 0; i < selectedList.size(); i++) {
				Category category = (Category) selectedList.get(i);
				str += category.getCateId();
				if (i != selectedList.size() - 1) {
					str += ",";
				}
			}
		}

		System.out.println(str);
		System.out.println(personDAO.findByCateList(str).size());
		return personDAO.findByCateList(str);
	}

	@SuppressWarnings("unchecked")
	public List<BigPerson> findByCate(Category category) {
		System.out.println(personDAO.findByCate(category).size());
		return personDAO.findByCate(category);
	}

	@SuppressWarnings("unchecked")
	public List<BigPerson> findNotInCate() {
		return personDAO.findNotInCate();
	}

	@SuppressWarnings("unchecked")
	public List<BigPerson> findAll() {
		return personDAO.findAll();
	}
}
